#include "udpthread.h"

udpthread::udpthread(QObject *parent) :
    QThread(parent)
{
    m_buf = new char[100*1024*1024];
    memset(m_buf,0,1024);

}
udpthread::~udpthread(){
    m_udpSocket->close();
    delete m_buf;
}

void udpthread::run(){
    m_udpSocket = new QUdpSocket(this);
    m_udpSocket->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption,8*1024*1024);
    m_udpSocket->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption,8*1024*1024);
    m_udpSocket->bind(QHostAddress::AnyIPv4,65522);
    m_udpSocket->joinMulticastGroup(QHostAddress("192.168.1.144"));

    connect(m_udpSocket , SIGNAL(readyRead()),this, SLOT(slotRecv()),Qt::DirectConnection);
    exec();
}

void udpthread::slotRecv(){

    qint64 mul=1024*62;
    qint64 c_init=1052+mul;

    char *recvBuf = new char[c_init];
    memset(recvBuf , 0, c_init);
    while(m_udpSocket->hasPendingDatagrams()){
        memset(recvBuf,0,c_init);
        int size = m_udpSocket->pendingDatagramSize();
        m_udpSocket->readDatagram(recvBuf,size);
        ImageFrameHead *mes = (ImageFrameHead *) recvBuf;
        if(mes->funCode == 24){
            memcpy(m_buf + mes ->uDataInFrameOffset,(recvBuf + sizeof(ImageFrameHead)),mes->uTransFrameSize);
            if(mes->uDataFrameCurr == mes->uDataFrameTotal){
                   qDebug("write over");
                   emit sigRecvOk(m_buf,mes->uDataFrameSize);
            }
        }
    }
    delete recvBuf;
}
